import transformConfig from 'sula/es/_util/transformConfig';
import isBoolean from 'lodash/isBoolean';
import { defaultSearchParams } from '@/services/global/base';
import { listToOptions } from '@/utils/utils';
import type { RequestOptionsInit } from 'umi-request';
import { request } from 'sula';
// 禁用sula错误提示
request.use({
  bizErrorMessageAdapter: () => {
    return null;
  },
} as any);

export const companyObjToList = (sourceData: companyList[]) => {
  const list = Array.isArray(sourceData) ? sourceData : [];
  const compList = list.map((compInfo) => {
    return {
      value: compInfo.companyId,
      text: `${compInfo.companyId}-@-${compInfo.companyName}`,
    };
  });
  return compList;
};

export const getContractSearchConfig = (config: any): RequestOptionsInit => {
  return {
    url: '/copyright/search',
    method: 'POST',
    disabledErrMsg: true,
    convertParams: isBoolean(config?.convertParams)
      ? (ctx: any) => {
          const { params, record } = ctx;
          // 初始化参数，覆盖优先级以函数行参最高依次合并
          const convertParamMerge = {
            ...defaultSearchParams,
            ...params,
            ...config?.params,
          };
          if (!record) return defaultSearchParams;
          // 主动调用sula模版转译，将参数中`${}`语言转换为上下文（ctx）中的参数
          const convertParam = transformConfig(convertParamMerge, ctx);

          const filters = { ...convertParam.filters };

          return {
            ...convertParam,
            filters,
          };
        }
      : config?.convertParams,
    converter: isBoolean(config?.converter)
      ? ({ data }: any) => {
          return listToOptions(data.list, 'copyrightId', 'contract');
        }
      : config?.converter,
  };
};
